<?php
if (! defined('IS_INITPHP'))
    exit('Access Denied!');
require_once 'Thrift/ClassLoader/ThriftClassLoader.php';
require_once 'Thrift/packages/RegisterService.php';
require_once 'Thrift/packages/Types.php';
require_once 'Thrift/Protocol/TProtocol.php';
require_once 'Thrift/Protocol/TCompactProtocol.php';
require_once 'Thrift/Transport/TTransport.php';
require_once 'Thrift/StringFunc/TStringFunc.php';
require_once 'Thrift/StringFunc/Core.php';
require_once 'Thrift/Factory/TStringFuncFactory.php';
require_once 'Thrift/Transport/TFramedTransport.php';
require_once 'Thrift/Exception/TException.php';
require_once 'Thrift/Exception/TTransportException.php';
require_once 'Thrift/Type/TType.php';
require_once 'Thrift/Type/TMessageType.php';
require_once 'Thrift/Transport/TSocket.php';
use com\meitu\api\thrift\service\RegisterServiceClient;
use Thrift\Transport\TSocket;
use Thrift\Transport\TFramedTransport;
use Thrift\Protocol\TCompactProtocol;

/**
 * Thrif 的使用封装类
 *
 * @author chendeben
 *        
 */
class thrifInit {

    private $host, $port;

    public function __construct() {
        $conf = InitPHP::getConfig();
        $thrifConf = $conf['Thrift'];
        $this->host = $thrifConf['host'];
        $this->port = $thrifConf['port'];
    }

    /**
     * 注册app
     *
     * @param string $app_key            
     * @param string $app_pwd            
     * @param string $app_salt            
     * @param string $need_auth            
     * @return Array ( [code] => -1 [message] => app key is already exist )
     */
    public function register($app_name, $app_desc, $app_key, $secret) {
        try {
            $transport = new TFramedTransport(new TSocket($this->host, $this->port));
            $transport->open();
        } catch (Exception $e) {
            writeLog(date("Y-m-d H:i:s") . "远程服务器 $this->host : $this->port 无法访问\r\n", "ServerError");
            die("无法打开$this->host:$this->port");
        }
        $protocol = new TCompactProtocol($transport);
        $register = new RegisterServiceClient($protocol);
        $result = $register->regist($app_key, $secret, MEITU_SALT, true, $app_name, $app_desc);
        $transport->close();
        $result = json_decode(json_encode($result), true);
        return $result;
    }

    public function getRegistInfo($app_key) {
        try {
            $transport = new TFramedTransport(new TSocket($this->host, $this->port));
            $transport->open();
        } catch (Exception $e) {
            writeLog(date("Y-m-d H:i:s") . "远程服务器 $this->host : $this->port 无法访问\r\n", "ServerError");
            die("无法打开$this->host:$this->port");
        }
        $protocol = new TCompactProtocol($transport);
        $register = new RegisterServiceClient($protocol);
        return $register->getRegistInfo($app_key);
    }
}